package com.livegoods.service;

import com.livegoods.commons.pojo.LivegoodsResult;
import com.livegoods.pojo.Item;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RecommendationProductServiceImpl implements RecommendationProductService {

    @Value("${livegoods.fastdfs.nginx}")
    private String fastdfsNginx;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public LivegoodsResult findHotRecommendationByCity(String city) {

        try {
            Criteria criteria1 = Criteria.where("city").is(city);//城市

            Criteria criteria2 = Criteria.where("recommendation").is(true);//热门

            Criteria criteria = new Criteria();
            //两个条件 and关系
            criteria.andOperator(criteria1,criteria2);

            Query query = new Query(criteria);
            //取4个，按照销量排序
            query.with(PageRequest.of(0,4));

            List<Item> items = mongoTemplate.find(query, Item.class);


            for (Item item : items) {
                item.setImg(fastdfsNginx+item.getImg());
            }



            return  LivegoodsResult.ok(items);
        } catch (Exception e) {
            e.printStackTrace();
            return LivegoodsResult.error("查询"+city+"的热门商品失败，请联系管理员...");
        }
    }
}
